#!/uva/bin/perl

# gen_vsource.pl
# by: Joseph F. Ryan 09/12/06
# usage: perl vsource.pl                      # output to screen
#        perl vsource.pl >out.txt             # output to a file
#        perl vsource.pl < input.txt >out.txt # output to a file, input from a file
# description:
# takes two 16bit or 32 bit binary strings and then spits out the
# vsource equivalant for them.  the output for the two strings will be separated
# by a single empty line.
# when inputting the numbers, spaces are allowed in order to visually aid the user

use strict;
use warnings;

message ("Enter input 1: (bitstring of either 32 bits or 16 bits): \n");
output_string('A',get_input());

print "\n\n";

message ("Enter input 2: (bitstring of either 32 bits or 16 bits): \n");
output_string('B',get_input());

sub get_input {
    while (1) {
        my $input = <>;
        chomp $input;
        
        # strip all spaces
        $input =~ s/\s//g;
        
        # check length
        if((length($input) != 16)
         &&(length($input) != 32)) {
            message("Input is not correct length; please enter input again: \n");
            redo;
        }
        
        # check for bad input characters
        if($input =~ /[^01]/) {
            warn("Input contains bad characters; please enter input again: \n");
            redo;
        }
        
        return split //, $input;
    };
}

sub output_string {
    my ($label,@bits) = @_;
    
    foreach my $i (0..$#bits) {
        print "\n" unless $i == 0;
        print "VDD", $i+1, " ($label$i 0) vsource dc=";
        print "pvdd" if  $bits[$i];
        print "0"    if !$bits[$i];
    }
}

# print messages that interact with the user to STDERR so that they won't
# show up when the output of the script is piped to a file
sub message {
    print STDERR @_;
}
